package com.example.frp_http_proxy

import mobile.Mobile
import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicBoolean

class FrpService : Service() {

    companion object {
        private const val TAG = "FrpService"
        private const val NOTIFICATION_ID = 1001
        private const val CHANNEL_ID = "frp_service_channel"
        private const val CHANNEL_NAME = "FRP Service"

        // 服务状态管理
        private val isRunning = AtomicBoolean(false)

        // 服务控制方法
        fun isServiceRunning(): Boolean = isRunning.get()

        // Intent 常量
        const val EXTRA_PORT = "port"
        const val EXTRA_NAME = "name"
        const val EXTRA_IP = "ip"
        const val ACTION_STOP = "com.example.frp_http_proxy.STOP_SERVICE"
    }

    private val serviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    private var currentJob: Job? = null

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        Log.d(TAG, "FrpService created")
    }

    override fun onBind(intent: Intent?): IBinder? {
        // 这是一个启动服务，不支持绑定
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "onStartCommand called with action: ${intent?.action}")

        when (intent?.action) {
            ACTION_STOP -> {
                stopFrpService()
                return START_NOT_STICKY
            }
            else -> {
                val port = intent?.getStringExtra(EXTRA_PORT)
                val name = intent?.getStringExtra(EXTRA_NAME)
                val ip = intent?.getStringExtra(EXTRA_IP)

                if (validateParameters(port, name, ip)) {
                    startFrpService(port!!, name!!, ip!!)
                } else {
                    Log.e(TAG, "Invalid parameters: port=$port, name=$name, ip=$ip")
                    stopSelf()
                    return START_NOT_STICKY
                }
            }
        }

        return START_STICKY
    }

    private fun validateParameters(port: String?, name: String?, ip: String?): Boolean {
        return !port.isNullOrBlank() && !name.isNullOrBlank() && !ip.isNullOrBlank()
    }

    private fun startFrpService(port: String, name: String, ip: String) {
        if (isRunning.get()) {
            Log.w(TAG, "Service is already running")
            return
        }

        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification("FRP服务运行中", "连接到: $ip:$port"))
        isRunning.set(true)

        // 取消之前的任务
        currentJob?.cancel()

        // 启动新的协程任务
        currentJob = serviceScope.launch {
            try {
                Log.i(TAG, "Starting FRP with parameters: port=$port, name=$name, ip=$ip")
                Mobile.run(port, name, ip)
                Log.i(TAG, "FRP service completed normally")
            } catch (e: CancellationException) {
                Log.i(TAG, "FRP service was cancelled")
                throw e
            } catch (e: Exception) {
                Log.e(TAG, "Error in Mobile.run: ${e.message}", e)
                // 更新通知显示错误状态
                updateNotification("FRP服务错误", "连接失败: ${e.message}")
            } finally {
                isRunning.set(false)
                Log.d(TAG, "FRP service task finished")
            }
        }
    }

    private fun stopFrpService() {
        Log.i(TAG, "Stopping FRP service")
        currentJob?.cancel()
        isRunning.set(false)
        stopForeground(true)
        stopSelf()
    }

    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                CHANNEL_NAME,
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "FRP代理服务通知"
                setShowBadge(false)
            }

            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    private fun createNotification(title: String, content: String): Notification {
        val stopIntent = Intent(this, FrpService::class.java).apply {
            action = ACTION_STOP
        }
        val stopPendingIntent = PendingIntent.getService(
            this, 0, stopIntent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )

        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle(title)
            .setContentText(content)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setOngoing(true)
            .addAction(android.R.drawable.ic_menu_close_clear_cancel, "停止", stopPendingIntent)
            .build()
    }

    private fun updateNotification(title: String, content: String) {
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(NOTIFICATION_ID, createNotification(title, content))
    }

    override fun onDestroy() {
        Log.d(TAG, "FrpService destroyed")
        currentJob?.cancel()
        serviceScope.cancel()
        isRunning.set(false)
        super.onDestroy()
    }
}
